package com.lemon.reggie.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lemon.reggie.common.BusinessException;
import com.lemon.reggie.pojo.dto.AddEmployeeDTO;
import com.lemon.reggie.pojo.dto.EditAndAbleDTO;
import com.lemon.reggie.pojo.dto.LoginDTO;
import com.lemon.reggie.pojo.entity.Employee;
import com.lemon.reggie.mapper.EmployeeMapper;
import com.lemon.reggie.service.EmployeeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lemon.reggie.utils.BaseContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.Objects;

/**
 * <p>
 * 员工信息 服务实现类
 * </p>
 *
 * @author Lemon
 * @since 2022-05-23
 */
@Slf4j
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {

    /**
     * 后台员工登录
     * @param loginDTO
     * @return com.lemon.reggie.pojo.entity.Employee
     * @author Guannankun
     * @since 2022/5/24
     */
    @Override
    public Employee login(LoginDTO loginDTO, HttpServletRequest request) {
        Employee employee = this.getOne(new LambdaQueryWrapper<Employee>()
                .eq(Employee::getUsername, loginDTO.getUsername()));

        if (employee == null) {
            throw new BusinessException("用户名不存在！");
        }

        String md5Password = DigestUtils.md5DigestAsHex(loginDTO.getPassword().getBytes());
        if (!Objects.equals(md5Password, employee.getPassword())) {
            throw new BusinessException("输入的用户名或密码错误！");
        }

        if (employee.getStatus() == 0) {
            throw new BusinessException("用户已被禁用，请联系管理员！");
        }

        //将Id存入session
        request.getSession().setAttribute("userInfo", employee.getId());
        return employee;
    }

    /**
     * 后台员工登出
     * @param request
     * @return void
     * @author Guannankun
     * @since 2022/5/24
     */
    @Override
    public void logout(HttpServletRequest request) {
        request.getSession().removeAttribute("userInfo");
    }

    /**
     * 员工分页
     * @param currentPage
     * @param pageSize
     * @param name
     * @return com.baomidou.mybatisplus.extension.plugins.pagination.Page<com.lemon.reggie.pojo.entity.Employee>
     * @author Guannankun
     * @since 2022/5/26
     */
    @Override
    public IPage<Employee> pageEmployee(Long currentPage, Long pageSize, String name) {
        IPage<Employee> iPage = new Page<>(currentPage, pageSize);
        return this.page(iPage, new LambdaQueryWrapper<Employee>()
                .like(StrUtil.isNotBlank(name), Employee::getName, name));
    }

    @Override
    public void addEmployee(AddEmployeeDTO addEmployeeDTO) {
        log.info("------当前请求的线程id为:{}", Thread.currentThread().getId());
        //添加账号唯一校验
        this.checkAddUserName(addEmployeeDTO.getUsername());

        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();

        this.save(Employee.builder()
                .name(addEmployeeDTO.getName())
                .username(addEmployeeDTO.getUsername())
                .password(DigestUtils.md5DigestAsHex("123456".getBytes(StandardCharsets.UTF_8)))
                .sex(addEmployeeDTO.getSex())
                .idNumber(addEmployeeDTO.getIdNumber())
                .phone(addEmployeeDTO.getPhone())
                .status(1)
               /* .createTime(LocalDateTime.now())
                .updateTime(LocalDateTime.now())
                .createUser((Long)request.getSession().getAttribute("userInfo"))
                .updateUser((Long)request.getSession().getAttribute("userInfo"))*/
                .build());

    }

    @Override
    public void enableAndDis(EditAndAbleDTO editAndAbleDTO) {
        log.info("------当前请求的线程id为:{}", Thread.currentThread().getId());
        //编辑账号唯一校验
        this.checkEditUserName(editAndAbleDTO.getUsername(),editAndAbleDTO.getId());

        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();

        this.updateById(Employee.builder()
                .id(Long.parseLong(editAndAbleDTO.getId()))
                .status(editAndAbleDTO.getStatus())
                .name(editAndAbleDTO.getName())
                .username(editAndAbleDTO.getUsername())
                .idNumber(editAndAbleDTO.getIdNumber())
                .phone(editAndAbleDTO.getPhone())
                .sex(editAndAbleDTO.getSex())
                .updateUser((Long) request.getSession().getAttribute("userInfo"))
                .updateTime(LocalDateTime.now())
                .build());
    }

    /**
     * 校验新增账号唯一
     * @param username
     * @return void
     * @author Guannankun
     * @since 2022/8/7
     */
    private void checkAddUserName(String username) {
        Employee one = this.getOne(new LambdaQueryWrapper<Employee>().eq(Employee::getUsername, username));
        if (one != null) {
            throw new BusinessException(username + "账号已存在，请重新输入！");
        }
    }

    /**
     * 校验编辑账号唯一
     * @param username
     * @param id
     * @return void
     * @author Guannankun
     * @since 2022/8/7
     */
    private void checkEditUserName(String username, String id) {
        Employee one = this.getOne(new LambdaQueryWrapper<Employee>()
                .eq(Employee::getUsername, username).ne(Employee::getId, Long.parseLong(id)));
        if (one != null) {
            throw new BusinessException(username + "账号已存在，请重新输入！");
        }
    }
}
